package com.icss.client.controller;

import com.icss.feign.UserService;
import com.icss.feign.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/* 登陆控制器*/
@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "login", method = RequestMethod.POST)

    public String login(@RequestParam("username") String userName, @RequestParam("password") String password, HttpServletResponse response, HttpServletRequest request) {
        try {
            User user = userService.queryByAccount(userName);
            if (user.getUser_pwd().equals(password)) {
                HttpSession session = request.getSession();
                session.setAttribute("userid", user.getUser_id());
                session.setAttribute("username", user.getUser_name());
                session.setAttribute("userstate", user.getUser_state());
                session.setMaxInactiveInterval(30 * 60);
                Cookie cookie = new Cookie("sessionId", session.getId());
                response.addCookie(cookie);
                userService.updateUserState(user.getUser_id());
                User loginUser = userService.queryByAccount(userName);
                if (loginUser != null && loginUser.getUser_id() > 0) {
                    userService.saveSession(loginUser);
                    //redisTemplate.boundSetOps("" + session.getId()).add(loginUser);
                    redisTemplate.opsForValue().set("" + session.getId(),loginUser);


                }
                return "home.html";
            }
            return "error.html";
        } catch (Exception ex) {
            return "error.html";
        }
    }

    @RequestMapping(value = "ssion", method = RequestMethod.GET)
    public User quresessid(HttpServletResponse response, HttpServletRequest reques) {
        User user = new User();
        Object userstate = reques.getSession().getAttribute("userstate");
        user.setUser_id((Integer) reques.getSession().getAttribute("userid"));
        user.setUser_name((String) reques.getSession().getAttribute("username"));
        user.setUser_state((Integer) reques.getSession().getAttribute("userstate"));
        return user;
    }

}
